<?php
declare (strict_types = 1);

namespace app\middleware;


use think\facade\Db;
use think\Response;
use think\Request;



class ApiLogin
{

    /**
     * 处理请求
     *
     * @param Request $request
     * @param \Closure    $next
     * @throws
     * @return Response
     */
    public function handle(Request $request, \Closure $next):Response
    {
        try {
            //获取登录token
            $token = $request->header('authorization');
            if (!$token) {
                throw new \Exception('您未登录，请登录后操作！');
            }

            //验证token
            $token_data = unserialize(encryptCode($token, 'DECODE', BASE_DOMAIN));
            if (!$token_data || !isset($token_data['uid']) || !isset($token_data['key'])) {
                throw new \Exception('登录环境发生变化，请重新登录！');
            }

            //查询登录状态
            $info = Db::name('member_login')->find($token_data['uid']);
            if (!$info) {
                throw new \Exception('您的账号被注销！');
            }

            //查询会员状态
            $user = Db::name('member')->find($info['member_id']);
            if (!$user['status']) {
                throw new \Exception('您的账号被冻结，请联系管理员！');
            }

            //验证单点登录
            $key = md5($info['member_id'] . '&' . $info['session_key'] . '&' . $info['last_login_time']);
            if ($key !== $token_data['key']) {
                throw new \Exception('您的账号已下线！');
            }

            return $next($request);
        }catch (\Exception $e){
            $err = [
                'code' => 4003,
                'msg' => $e->getMessage(),
                'data' => []
            ];
            json($err)->send();exit;
        }
    }
}
